#include "SearchDB.h"

SearchDB::SearchDB(QWidget *parent):
	QWidget(parent),
	mParent(parent),
    mSearchWordID(-1),
    mSearchWord(""),
    mCurWord(NULL)
{
	ui.setupUi(this);
	ui.customListEdit->setInputMask("999");

	QObject::connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(search()));
	QObject::connect(ui.closeButton, SIGNAL(clicked()), this, SLOT(hide()));
	QObject::connect(ui.setCustomListButton, SIGNAL(clicked()), this, SLOT(updateCustomListInfo()));

	QShortcut* searchShortcut = new QShortcut(QKeySequence(Qt::Key_Return),  this);
	QObject::connect(searchShortcut,SIGNAL(activated()),this,SLOT(search()));

	QShortcut* closeShortcut = new QShortcut(QKeySequence(Qt::Key_Escape),  this);
	QObject::connect(closeShortcut,SIGNAL(activated()),this,SLOT(hide()));

	QShortcut* setCustomListShortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return),  this);
	QObject::connect(setCustomListShortcut,SIGNAL(activated()),this,SLOT(updateCustomListInfo()));
}


SearchDB::~SearchDB()
{

}

void SearchDB::search()
{
	mSearchWord = ui.wordLineEdit->text();
	ui.wordLineEdit->selectAll();
	if (!mSearchWord.isEmpty())
	{
		QString queryCommand;
		queryCommand = QString("select id from words where English='%1'; ").arg(mSearchWord);
		cout<<"SearchDB::search-->mSearchWord="<<mSearchWord.toUtf8().data()<<endl;
		DB.quickGet(queryCommand);
		int id;
		if (DB.getRowCount()>0) id = DB.getTableValue(0,"id").toInt();
		else id = 0;
		ui.displayArea->getTextBrowser()->clear();
		if (id == 0)
		{
			//search failed
			QString errInfo = QString("<FONT color=red>Fail to find word '%1 in GRE red bible.'</FONT><BR><BR>").arg(mSearchWord);
			ui.displayArea->getTextBrowser()->insertHtml(errInfo);
			//try further search
			ui.displayArea->getTextBrowser()->insertHtml(DM.quickLookup(mSearchWord));
		}
		else
		{
			cout<<"SearchDB::search-->id="<<id<<endl;
			mSearchWordID = id;
			if (mCurWord)
				delete mCurWord;
			mCurWord = new Word(mSearchWordID);

			showBasicInfo();
			showHistoryInfo();
			showCustomListInfo();
		}
	}
}

void SearchDB::showBasicInfo()
{
	cout<<"SearchDB::showBasicInfo"<<endl;
	QString queryCommand;
	vector<QString>requirements;

	//get basic information
	queryCommand.clear();
	requirements.clear();
	requirements.push_back("id");
	requirements.push_back("English");
	requirements.push_back("soundmark");
	requirements.push_back("exp_red_bible");

	queryCommand.append("select ");
	for (int i=0; i<requirements.size()-1; i++)
		queryCommand.append(requirements[i]).append(", ");
	queryCommand.append(requirements[requirements.size()-1]);
	queryCommand.append(QString(" from words where id=%1;").arg(mSearchWordID));
	DB.quickGet(queryCommand);

	QString English = DB.getTableValue(0,"English");
	QString soundmark = DB.getTableValue(0,"soundmark");
	QString exp_red_bible = DB.getTableValue(0,"exp_red_bible");

	//cout<<"queryCommand="<<queryCommand.toUtf8().data()<<endl;
	mCurWord->setEnglish(English);
	mCurWord->setSoundMark(soundmark);
	mCurWord->setRedBibleExp(exp_red_bible);//essential

	//display word
	ui.displayArea->getTextBrowser()->insertHtml(mCurWord->getEnglish());
	ui.displayArea->getTextBrowser()->insertHtml("<br>");
	QString soundMark = mCurWord->getSoundMark();
	soundMark.replace(QString::fromUtf8("0"), QString::fromUtf8("ð"));
	soundMark.replace(QString::fromUtf8("1"), QString::fromUtf8("æ"));
	soundMark.replace(QString::fromUtf8("2"), QString::fromUtf8("ɑ"));
	soundMark.replace(QString::fromUtf8("3"), QString::fromUtf8("ɒ"));
	soundMark.replace(QString::fromUtf8("4"), QString::fromUtf8("ә"));
	soundMark.replace(QString::fromUtf8("5"), QString::fromUtf8("ʃ"));
	soundMark.replace(QString::fromUtf8("6"), QString::fromUtf8("ŋ"));
	soundMark.replace(QString::fromUtf8("7"), QString::fromUtf8("θ"));
	soundMark.replace(QString::fromUtf8("8"), QString::fromUtf8("ʌ"));
	soundMark.replace(QString::fromUtf8("9"), QString::fromUtf8("ʒ"));
	soundMark.replace(QString::fromUtf8("A"), QString::fromUtf8("є"));
	soundMark.replace(QString::fromUtf8("W"), QString::fromUtf8(""));
	soundMark.replace(QString::fromUtf8("I"), QString::fromUtf8("i"));
	soundMark.prepend("[");
	soundMark.append("]<br>");
	ui.displayArea->getTextBrowser()->insertHtml(soundMark);

	ui.displayArea->getTextBrowser()->insertHtml(mCurWord->getRedBibleExp());
	ui.displayArea->getTextBrowser()->insertHtml("<br>");

	//ui.detailDisplay->insertHtml(DM.getAllExplanations(mCurWord->getEnglish()));
	ui.displayArea->getTextBrowser()->insertHtml(DM.quickLookup(mCurWord->getEnglish()));
	/*QVector<QString>& dictList = WM.getDictList();
	for(int i=0; i<dictList.size(); i++)
	{
		ui.detailDisplay->insertHtml(mCurWord->getExplanation(dictList[i]));
		ui.detailDisplay->insertHtml("<br>");
	}*/
}

void SearchDB::showHistoryInfo()
{
	QString queryCommand;
	vector<QString>requirements;
	ui.historyDisplay->clear();
	//get list information
	queryCommand.clear();
	queryCommand = QString("select id,custom_list,red_bible_list from lists where id=%1;").arg(mSearchWordID);
	DB.quickGet(queryCommand);
	QString idString = QString("%1").arg(mSearchWordID);
	QString customList = DB.getTableValue(0,"custom_list");
	QString redBibleList = DB.getTableValue(0,"red_bible_list");
	ui.historyDisplay->insertHtml("Location: <br>");
	ui.historyDisplay->insertHtml(QString("<B>ID: %1.</B><br>").arg(mSearchWordID));
	ui.historyDisplay->insertHtml(QString("<FONT color=red>Red Bible: %1.</FONT><br>").arg(redBibleList));
	ui.historyDisplay->insertHtml(QString("<FONT color=green><B>Custom List: %1.</B></FONT><br>").arg(customList));
	//ui.historyDisplay->insertHtml("<hr>");
	//get history information
	queryCommand.clear();
	requirements.clear();
	requirements.push_back("difficulty_level");
	requirements.push_back("importance_level");
	requirements.push_back("last_reciting_status");
	requirements.push_back("recite_date_history");
	requirements.push_back("memory_level");
	requirements.push_back("memory_level_delta");

	queryCommand.append("select ");
	for(int i=0; i<requirements.size()-1; i++)
		queryCommand.append(requirements[i]).append(",");
	queryCommand.append(requirements[requirements.size()-1]);
	queryCommand.append(QString(" from history where id = %1").arg(mSearchWordID));
	DB.quickGet(queryCommand);

	//cout<<"queryCommand="<<queryCommand.toUtf8().data()<<endl;
	int difficulty_level = DB.getTableValue(0,"difficulty_level").toInt();
	int importance_level = DB.getTableValue(0,"importance_level").toInt();
	int last_reciting_status = DB.getTableValue(0,"last_reciting_status").toInt();
	QString recite_date_history = DB.getTableValue(0,"recite_date_history");
	int memory_level = DB.getTableValue(0,"memory_level").toInt();
	int memory_level_delta = DB.getTableValue(0,"memory_level_delta").toInt();

	//cout<<"difficulty_level="<<difficulty_level<<endl;
	//cout<<"last_reciting_status="<<last_reciting_status.toUtf8().data()<<endl;
	mCurWord->setMemoryLevel(memory_level);
	mCurWord->setMemoryLevelDelta(memory_level_delta);
	mCurWord->setDifficultyLevel(difficulty_level);
	mCurWord->setImportanceLevel(importance_level);
	mCurWord->setWordStatus(last_reciting_status);
	mCurWord->setReciteDateHistory(recite_date_history);

	int reciteCount =mCurWord->getTotalReciteCount();
	QString reciteCountString;
	if (reciteCount == 0)
		reciteCountString = QString("Recite count: <FONT COLOR=red>%1</FONT>.").arg(reciteCount);
	else
		reciteCountString = QString("Recite count: %1.").arg(reciteCount);
	ui.historyDisplay->insertHtml(reciteCountString + "<br>");
	QStringList reciteDateList =  mCurWord->getReciteDateString();
	ui.historyDisplay->insertHtml("Recite date: <br>");
	for (int i=0; i<reciteDateList.size(); i++)
		ui.historyDisplay->insertHtml(reciteDateList[i] + "<br>");
	//ui.historyDisplay->insertHtml(QString("GPR: %1.<br>").arg(mCurWord->getGrossPassRate()));
	ui.historyDisplay->insertHtml(QString("DL: %1.<br>").arg(mCurWord->getDifficultyLevel()));
}

void SearchDB::showCustomListInfo()
{
	QString queryCommand;
	queryCommand = QString("select id,custom_list from lists where id=%1;").arg(mSearchWordID);
	DB.quickGet(queryCommand);
	QString customList = DB.getTableValue(0,"custom_list");

	if (customList != "0")
		ui.customListEdit->setText(customList);
	else
	{
		queryCommand = "select max(custom_list) from lists;";
		DB.quickGet(queryCommand);
		int maxCustomList = DB.getTableValue(0,"max(custom_list)").toInt();
		ui.customListEdit->setText(QString("%1").arg(maxCustomList));
	}
}

void SearchDB::updateCustomListInfo()
{
	if (mSearchWordID > 0)
	{
		QString queryCommand;
		int listID = ui.customListEdit->text().toInt();
		queryCommand = QString("update lists set custom_list=%1").arg(listID);
		queryCommand.append(QString(" where id = %1;").arg(mSearchWordID));
		DB.quickUpdate(queryCommand);
		showHistoryInfo();
	}
}

void SearchDB::show()
{
	ui.wordLineEdit->setFocus();
	ui.wordLineEdit->selectAll();
	float sizeRate = 0.7f;
	this->setGeometry(
					OPT.mainWindowX+(1-sizeRate)*OPT.mainWindowWidth/2,
					OPT.mainWindowY+(1-sizeRate)*OPT.mainWindowHeight/2,
					OPT.mainWindowWidth*sizeRate,
					OPT.mainWindowHeight*sizeRate);
	QWidget::show();
}

void SearchDB::hideSearchBar()
{
	ui.wordLineEdit->hide();
	ui.searchButton->hide();
}

void SearchDB::showSearchBar()
{
	ui.wordLineEdit->show();
	ui.searchButton->show();
}

/*
void SearchDB::hide()
{
	QWidget::hide();
	mParent->raise();
	mParent->activateWindow();
}*/

